package ma.jeetconsulting.pocs.service;

import java.util.Map;
import java.util.Set;

import ma.jeetconsulting.pocs.dependency.util.Booter;
import ma.jeetconsulting.pocs.dependency.util.ConsoleDependencyGraphDumper;

import org.sonatype.aether.RepositorySystem;
import org.sonatype.aether.RepositorySystemSession;
import org.sonatype.aether.artifact.Artifact;
import org.sonatype.aether.collection.CollectRequest;
import org.sonatype.aether.collection.CollectResult;
import org.sonatype.aether.collection.DependencyCollectionException;
import org.sonatype.aether.graph.Dependency;
import org.sonatype.aether.repository.RemoteRepository;
import org.sonatype.aether.util.artifact.DefaultArtifact;

public class DependenciesAnalyzerImpl implements DependenciesAnalyzer {

	@Override
	public CollectResult getTheDependecyTree(String groupId, String artifactId, String version) {
		CollectResult collectResult = null;

		try {
			collectResult = tryToGetDependeciesCollectionResult(groupId + ":" + artifactId + ":" + version);
			collectResult.getRoot().accept( new ConsoleDependencyGraphDumper() );
		} catch (DependencyCollectionException e) {
			e.printStackTrace();
			return collectResult;
		}

		return collectResult;
	}

	private CollectResult tryToGetDependeciesCollectionResult(String artifactString) throws DependencyCollectionException {
		Artifact artifact = new DefaultArtifact(artifactString);
		CollectRequest collectRequest = new CollectRequest();
		RemoteRepository remoteRepository = new RemoteRepository( "central", "default", "http://repo1.maven.org/maven2/" );
		
		RepositorySystem RepositorySystem = Booter.newRepositorySystem();
		RepositorySystemSession repositorySystemSession = Booter.newRepositorySystemSession(RepositorySystem);
		
		setToRequestRemoteRepositoriesAndRootArtifact(collectRequest, artifact, remoteRepository);
		
		
		return RepositorySystem.collectDependencies(repositorySystemSession, collectRequest);
	}

	private void setToRequestRemoteRepositoriesAndRootArtifact(
			CollectRequest collectRequest, Artifact artifact, RemoteRepository ... remoteRepositories) {
		for (RemoteRepository remoteRepository : remoteRepositories) {
			collectRequest.addRepository(remoteRepository);
		}
		collectRequest.setRoot(new Dependency(artifact, ""));
	}

	@Override
	public Map<Dependency, Dependency> getDependenciesToMigrate(
			Dependency oldDependency, Dependency recentDependency) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void MigrationAnalysis(Dependency dependency,
			Set<Dependency> targetDependecies) {
		// TODO Auto-generated method stub

	}

}
